package com.wocai.jrt.orgadmin.pay.action;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.common.BigDecimalUtils;
import com.vteba.utils.date.DateUtils;
import com.vteba.utils.json.FastJsonUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.model.EmployeeCommissionHistory;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeCommissionHistoryService;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.pay.bean.CommissionPayEmpResBean;
import com.wocai.jrt.orgadmin.pay.bean.CommissionPayReqBean;
import com.wocai.jrt.orgadmin.pay.bean.CommissionPayResBean;
import com.wocai.jrt.orgadmin.pay.bean.CommissionPayTotalReqBean;
import com.wocai.jrt.orgadmin.pay.bean.CommissionPayTotalResBean;
import com.wocai.jrt.orgadmin.pay.bean.SettleAllReqBean;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 支付流水控制器
 * 
 * @author yinlei
 * @date 2015-8-24 10:23:36
 */
@Controller
@RequestMapping("/commissionPay")
public class CommissionPayAction extends GenericAction<EmployeeCommissionHistory> {
	private static final Logger LOGGER = LoggerFactory.getLogger(CommissionPayAction.class);
	private static final String STAT_FILE_NAME = "员工佣金报表";
	@Inject
	private EmployeeCommissionHistoryService employeeCommissionHistoryServiceImpl;

	@Inject
	private EmployeeService employeeServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获取佣金查询页面，仅仅只是页面而已
	 * 
	 * @param model
	 *            参数
	 * @return 产品List
	 */
	@RequestMapping("/listTotal")
	public String listTotal(CommissionPayReqBean commissionPayReqBean,Model model) {
		if(commissionPayReqBean.getPayStartTime() != null){
			model.addAttribute("payStartTime",DateUtils.toDateString(commissionPayReqBean.getPayStartTime(), "yyyy-MM-dd"));
		}
		if(commissionPayReqBean.getPayEndTime() != null){
			model.addAttribute("payEndTime",DateUtils.toDateString(commissionPayReqBean.getPayEndTime(), "yyyy-MM-dd"));
		}
		if(commissionPayReqBean.getProductSearch() != null){
			model.addAttribute("productSearch",commissionPayReqBean.getProductSearch());
		}
		if(commissionPayReqBean.getProductId() != null){
			model.addAttribute("productId",commissionPayReqBean.getProductId());
		}
		if(commissionPayReqBean.getState() != null){
			model.addAttribute("state",commissionPayReqBean.getState());
		}
		return "pay/commission-list";
	}
	
	/**
	 * 获取佣金统计页面，仅仅只是页面而已
	 * 
	 * @param model
	 *            参数
	 * @return 产品List
	 */
	@RequestMapping("/list")
	public String list(CommissionPayReqBean model) {
		return "pay/commission";
	}
	
	/**
	 * 获取支付流水页面，仅仅只是页面而已
	 * 
	 * @param model
	 *            参数
	 * @return 产品List
	 */
	@RequestMapping("/empList/{employeeId}")
	public String empList(@PathVariable("employeeId") String employeeId, Model model) {
		model.addAttribute("employeeName",employeeServiceImpl.get(employeeId).getName());
		return "pay/commission-list-employee";
	}

	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/queryTotal")
	public Map<String, Object> queryTotal(@RequestBody CommissionPayTotalReqBean model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request CommissionPayResBean query, param = [{}]",
					JSON.toJSONString(model));

			model.setOrgId(UserUtils.getUser().getOrgId());

			if (null != model.getPayEndTime()) {
				model.setPayEndTime(new DateTime(model.getPayEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			int size = employeeCommissionHistoryServiceImpl.fetchTotalCount(model);

			List<CommissionPayTotalResBean> list = new ArrayList<CommissionPayTotalResBean>();
			List<CommissionPayTotalResBean> list1 = new ArrayList<CommissionPayTotalResBean>();
			if (size > 0) {
				list = employeeCommissionHistoryServiceImpl.fetchCommissionTotalPay(model);
				model.setStart(null);
				list1 = employeeCommissionHistoryServiceImpl.fetchCommissionTotalPay(model);
				LOGGER.info("query CommissionPayResBean list success, size = [{}]", list.size());

			}
			
			
			Double sumOrderAmount = 0.0;
			Double sumCommission = 0.0;
			Double sumSettle = 0.0;
			Double sumUnsettle = 0.0;
			Iterator<CommissionPayTotalResBean> iter = list1.iterator();
			while (iter.hasNext()) {
				CommissionPayTotalResBean c = iter.next();
				if (c.getOrderTotalAmount() != null) {
					sumOrderAmount = BigDecimalUtils.add(sumOrderAmount, c.getOrderTotalAmount());
				}
				if (c.getTotalCommission() != null) {
					sumCommission = BigDecimalUtils.add(sumCommission, c.getTotalCommission());
				}
				if(c.getSettledAmount() != null){
					sumSettle = BigDecimalUtils.add(sumSettle, c.getSettledAmount());
				}
				if(c.getUnsettledAmount() != null){
					sumUnsettle = BigDecimalUtils.add(sumUnsettle, c.getUnsettledAmount());
				}
			}
			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数
			map.put("sumOrderAmount", sumOrderAmount);
			map.put("sumCommission", sumCommission);
			map.put("sumSettle", sumSettle);
			map.put("sumUnsettle", sumUnsettle);

		} catch (Exception e) {
			LOGGER.error("request CommissionPayResBean query error, msg = [{}]", e.getMessage());
		}

		return map;
	}
	
	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/queryEmp")
	public Map<String, Object> queryEmp(@RequestBody CommissionPayReqBean model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request CommissionPayResBean query, param = [{}]",
					JSON.toJSONString(model));

			model.setOrgId(UserUtils.getUser().getOrgId());

			if (null != model.getPayEndTime()) {
				model.setPayEndTime(new DateTime(model.getPayEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			int size = employeeCommissionHistoryServiceImpl.fetchEmpCount(model);
			if (model.getPageSize() == -1) {
				model.setStart(null);
			}

			List<CommissionPayEmpResBean> list = new ArrayList<CommissionPayEmpResBean>();

			if (size > 0) {
				list = employeeCommissionHistoryServiceImpl.fetchCommissionEmpPay(model);
				LOGGER.info("query CommissionPayResBean list success, size = [{}]", list.size());

			}

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request CommissionPayResBean query error, msg = [{}]", e.getMessage());
		}

		return map;
	}
	
	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody CommissionPayReqBean model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request CommissionPayResBean query, param = [{}]",
					JSON.toJSONString(model));

			model.setOrgId(UserUtils.getUser().getOrgId());

			if (null != model.getPayEndTime()) {
				model.setPayEndTime(new DateTime(model.getPayEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			int size = employeeCommissionHistoryServiceImpl.fetchCount(model);
			if (model.getPageSize() == -1) {
				model.setStart(null);
			}

			List<CommissionPayResBean> list = new ArrayList<CommissionPayResBean>();

			if (size > 0) {
				list = employeeCommissionHistoryServiceImpl.fetchCommissionPay(model);
				LOGGER.info("query CommissionPayResBean list success, size = [{}]", list.size());

			}

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request CommissionPayResBean query error, msg = [{}]", e.getMessage());
		}

		return map;
	}

	/**
	 * 查看支付流水详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 支付流水详情页
	 */
	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			CommissionPayReqBean cprParam = new CommissionPayReqBean();
			cprParam.setId(id);
			cprParam.setOrgId(UserUtils.getUser().getOrgId());
			List<CommissionPayResBean> model = employeeCommissionHistoryServiceImpl
					.fetchCommissionPay(cprParam);
			CommissionPayResBean commissionPayResBean = model.get(0);
			Integer state = commissionPayResBean.getState();
			if (null == state || state == 0) {
				commissionPayResBean.setAuditId(null);
				commissionPayResBean.setAuditName(null);
				commissionPayResBean.setAuditTime(null);
				commissionPayResBean.setcPayId(null);
				commissionPayResBean.setcPayName(null);
				commissionPayResBean.setcPayTime(null);
			} else if (state == 1) {
				Employee employee = employeeServiceImpl.get(commissionPayResBean.getAuditId());
				commissionPayResBean.setAuditName(employee.getName());
				commissionPayResBean.setcPayId(null);
				commissionPayResBean.setcPayName(null);
				commissionPayResBean.setcPayTime(null);
			} else {
				Employee employee1 = employeeServiceImpl.get(commissionPayResBean.getAuditId());
				commissionPayResBean.setAuditName(employee1.getName());
				Employee employee2 = employeeServiceImpl.get(commissionPayResBean.getcPayId());
				commissionPayResBean.setcPayName(employee2.getName());
			}
			maps.put("commissionPayResBean", commissionPayResBean);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "pay/commission-detail";
	}

	/**
	 * 更新支付流水信息
	 * 
	 * @param model
	 *            要更新的支付流水信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/audit/{id}/{flag}")
	public JsonBean audit(@PathVariable("id") String id, @PathVariable("flag") Integer flag) {
		JsonBean bean = new JsonBean();
		try {
			EmployeeCommissionHistory model = new EmployeeCommissionHistory();
			model.setId(id);
			if (null != flag) {
				if (flag == 1) {
					model.setAuditId(UserUtils.getUser().getEmployeeId());
					model.setState(flag);
					model.setAuditTime(new Date());
				} else if (flag == 2) {
					model.setcPayId(UserUtils.getUser().getEmployeeId());
					model.setState(flag);
					model.setcPayTime(new Date());
				}
			}

			int result = employeeCommissionHistoryServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
	
	/**
	 * 全部结算功能
	 * @param allocateOrgDeviceReqBean
	 * @return
	 */
	@ResponseBody
    @RequestMapping("/settleAll")
	public JsonBean settleAll(@RequestBody SettleAllReqBean settleAllReqBean){
		JsonBean json = new JsonBean();
		if(StringUtils.isAnyBlank(settleAllReqBean.getCommissionHistoryIdList().toString())){
			json.setCode(0);
			json.setMessage("参数为空");
			return json;
		}
		
		settleAllReqBean.setcPayTime(new Date());
		settleAllReqBean.setEmployeeId(UserUtils.getUserId());
		long result = employeeCommissionHistoryServiceImpl.settleAll(settleAllReqBean);
		if(result == settleAllReqBean.getCommissionHistoryIdList().size()){
			json.setCode(1);
			json.setMessage(SUCCESS);
		}else{
			json.setCode(0);
			json.setMessage(ERROR);
		}
		return json;
	}
	
	/**
	 * 结算功能
	 * @param allocateOrgDeviceReqBean
	 * @return
	 */
	@ResponseBody
    @RequestMapping("/settle")
	public JsonBean settle(@RequestBody EmployeeCommissionHistory ech){
		JsonBean json = new JsonBean();
		if(StringUtils.isAnyBlank(ech.getId())){
			json.setCode(0);
			json.setMessage("参数为空");
			return json;
		}
		ech = employeeCommissionHistoryServiceImpl.get(ech.getId());
		if (2 == ech.getState()) {
			json.setCode(0);
			json.setMessage("该佣金已结算");
			return json;
		}
		ech.setcPayId(UserUtils.getUserId());
		ech.setcPayTime(new Date());
		ech.setState(2);
		
		long result = employeeCommissionHistoryServiceImpl.updateById(ech);
		if(result == 1){
			json.setCode(1);
			json.setMessage(SUCCESS);
		}else{
			json.setCode(0);
			json.setMessage(ERROR);
		}
		return json;
	}
	
	/**
	 * 查询产品销售报表。
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@RequestMapping("/statsDownload")
	public String productEmpStatsDownload(String params, HttpServletResponse response) {
		try {
			CommissionPayTotalReqBean model = FastJsonUtils.fromJson(params, CommissionPayTotalReqBean.class);
			LOGGER.info("request CommissionPayResBean query, param = [{}]",
					JSON.toJSONString(model));
			model.setOrgId(UserUtils.getUser().getOrgId());

			if (null != model.getPayEndTime()) {
				model.setPayEndTime(new DateTime(model.getPayEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			int size = employeeCommissionHistoryServiceImpl.fetchTotalCount(model);

			List<CommissionPayTotalResBean> list = new ArrayList<CommissionPayTotalResBean>();

			if (size > 0) {
				model.setStart(null);
				list = employeeCommissionHistoryServiceImpl.fetchCommissionTotalPay(model);
				LOGGER.info("query CommissionPayResBean list success, size = [{}]", list.size());
			}
			
			Double sumOrderAmount = 0.0;
			Double sumCommission = 0.0;
			Double sumSettle = 0.0;
			Double sumUnsettle = 0.0;
			Iterator<CommissionPayTotalResBean> iter = list.iterator();
			while (iter.hasNext()) {
				CommissionPayTotalResBean c = iter.next();
				if (c.getOrderTotalAmount() != null) {
					sumOrderAmount = BigDecimalUtils.add(sumOrderAmount, c.getOrderTotalAmount());
				}
				if (c.getTotalCommission() != null) {
					sumCommission = BigDecimalUtils.add(sumCommission, c.getTotalCommission());
				}
				if(c.getSettledAmount() != null){
					sumSettle = BigDecimalUtils.add(sumSettle, c.getSettledAmount());
				}
				if(c.getUnsettledAmount() != null){
					sumUnsettle = BigDecimalUtils.add(sumUnsettle, c.getUnsettledAmount());
				}
			}
			
			String[] columnHead = {"总计", " ","销售总额: "+sumOrderAmount, "佣金总额: "+sumCommission,  "已结算总额: "+sumSettle, "未结算总额: "+sumUnsettle};
			String[] columns = {"理财师姓名", "理财师工号", "销售总额", "佣金总额", "已结算", "未结算"};
			
			List<Object[]> exportList = new ArrayList<Object[]>();
			
			for (CommissionPayTotalResBean ech:list ) {
				Object[] object = new Object[6];
				object[0] = ech.getEmployeeName();
				object[1] = ech.getEmployeeNo();
				object[2] = ech.getOrderTotalAmount();
				object[3] = ech.getTotalCommission();
				object[4] = ech.getSettledAmount();
				object[5] = ech.getUnsettledAmount();
				exportList.add(object);
			}
			// 创建新的Excel 工作簿
	        HSSFWorkbook workbook = new HSSFWorkbook();
	 
	        // 在Excel工作簿中建一工作表，其名为缺省值。
	        // 也可以指定工作表的名字。
	        HSSFSheet sheet = workbook.createSheet("Table");
	         
	        // 下面将建立一个表。第一行为表头。
	        int rowNum = 0;// 行标
	        int colNum = 0;// 列标
	        // 建立表头信息
	        // 在索引0的位置创建行（最顶端的行）
	        HSSFRow row = sheet.createRow(rowNum);
	        
	        // 单元格
	        HSSFCell cell = null;
	        for (colNum = 0; colNum < columnHead.length; colNum++) {
	            // 在当前行的colNum列上创建单元格
	            cell = row.createCell(colNum);
	            // 定义单元格为字符类型，也可以指定为日期类型、数字类型
	            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
	            // 添加内容至单元格
	            cell.setCellValue(columnHead[colNum]);
	        }
	        rowNum++;
	        HSSFRow row1 = sheet.createRow(rowNum);
	        for (colNum = 0; colNum < columns.length; colNum++) {
	            // 在当前行的colNum列上创建单元格
	            cell = row1.createCell(colNum);
	            // 定义单元格为字符类型，也可以指定为日期类型、数字类型
	            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
	            // 添加内容至单元格
	            cell.setCellValue(columns[colNum].toString());
	        }
	        rowNum++;
	        for (; rowNum < exportList.size() + 2; rowNum++) {
	        	Object[] ctr = exportList.get(rowNum - 2);
	            // 新建第rowNum行
	            row = sheet.createRow(rowNum);
	            for (colNum = 0; colNum < columns.length; colNum++) {
	                // 在当前行的colNum位置创建单元格
	                cell = row.createCell(colNum);
	                //宽度
	                sheet.setColumnWidth(colNum,30*256); 	
	                //写入值
	                cell.setCellValue(ctr[colNum].toString());
	            }
	        }
			
			String filename = STAT_FILE_NAME + DateUtils.toDateString("yyyyMMddHHmmss") + ".xls";
			
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
			
			OutputStream out = response.getOutputStream();
			workbook.write(out);
			
			out.flush();
			out.close();
			workbook.close();
			response.flushBuffer();
		} catch (Exception e) {
			//e.printStackTrace();
			LOGGER.error("download file error, error=[{}]", e.getMessage());
		}
		return null;
	}
}
